<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Menu_Models_Mysql_Item extends Modules_Menu_Models_Item
{	
	protected $_table = 'menu_item';
	
	public function add($item)
	{
		$sql = sprintf("INSERT INTO " . $this->_conn->_tablePrefix . $this->_table . " (item_id, label, link, menu_id, left_id, right_id, parent_id)
						VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')",
						$this->_conn->escape($item['item_id']),
						$this->_conn->escape($item['label']),
						$this->_conn->escape($item['link']),
						$this->_conn->escape($item['menu_id']),
						$this->_conn->escape($item['left_id']),
						$this->_conn->escape($item['right_id']),
						$this->_conn->escape($item['parent_id']));
						
		$this->_conn->query($sql);
		return $this->_conn->lastInsertId();	
	}
	
	public function delete($menuId)
	{
		$sql = sprintf("DELETE FROM " . $this->_conn->_tablePrefix . $this->_table . " 
						WHERE menu_id = '%s'", 
						$this->_conn->escape($menuId));
						
		mysql_query($sql);
		return mysql_affected_rows();
	}

	public function getTree($menuId)
	{
		$sql = sprintf("SELECT node.item_id, node.label, node.link, (COUNT(parent.item_id) - 1) AS depth,
							node.left_id, node.right_id, node.parent_id
						FROM " . $this->_conn->_tablePrefix . $this->_table . " AS node,
							" . $this->_conn->_tablePrefix . $this->_table . " AS parent
						WHERE node.menu_id = '%s' 
							AND parent.menu_id = '%s' 
							AND node.left_id BETWEEN parent.left_id AND parent.right_id
						GROUP BY node.item_id
						ORDER BY node.left_id",
						$menuId,
						$menuId);
						
		$rs   = $this->_conn->query($sql);
		$rows = array();
		while ($row = $this->_conn->fetchAll($rs)) {
			$rows[] = $row;
		}
		$this->_conn->freeResult($rs);
		return $rows;		
	}
}
